import React from 'react'
// ===================================================================== Temp
import SearchForm from '#cpt/temp/SearchForm'
import Table from '#cpt/temp/Table'
import TableControls from '#cpt/temp/TableControls'
import FormModal from '#cpt/temp/FormModal'
import Controls from '#cpt/temp/Controls'
import Confirm from '#cpt/temp/Confirm'
import Tabs from '#tp/tabs/tabs'
// ===================================================================== global declare
const { $fn, $Lazy } = window
// ===================================================================== Lazy
const Page 				= $Lazy.load(()=>import('#tp/page/page-container'))
const $cache 			= $Lazy.file(()=>import('#private/cache-api'))
const ChecAccessoryModal= $Lazy.state(()=>import('./cpt/check-accessory-modal'))
const AuditModal		= $Lazy.state(()=>import('./cpt/audit-modal'))
const AbortModal		= $Lazy.state(()=>import('./cpt/abort-modal'))
const TipModal		= $Lazy.state(()=>import('./cpt/tip-modal'))
// ===================================================================== data
const tabsData = [{ title:'全部', status:'99', value:'99' },{ title:'草稿', status:'0', value:'0' },{ title:'待审核', status:'5', value:'5'},
	{ title:'已审核', status:'1', value:'1' },{ title:'未通过', status:'4', value:'4' },{ title:'已过期', status:'2', value:'2' },{ title:'已终止', status:'3', value:'3' }]
const contractType = [{name:'预备合同', value:'1'},{name:'正式合同', value:'2'}]
// ===================================================================== component
class Index extends React.Component{
	state = {
		data:[],
		selectedKeys:[],
		pag: {},
		// 搜索表单列表
		forms : [
			{ label: '合同编号',		name: 'code' },
			{ label: '合同名称',		name: 'name' },
			{ label: '客户名称',		name: 'hosp_id',	type: 'select', loading:true,nameStr:'name', onValue:({ rows }) => {
				this.model.hosp_name = rows ? rows.name : ''
			} },
			{ label: '合同失效',		name: 'invalid',	type: 'select', data:[{ name:'请选择', value: '' },{ name:'7天内', value: '7' },{ name:'15天内', value: '15' }, { name:'1个月内', value: '31' }] },
			{ label: '到期时间',		names: ['start_at','end_at'],	type: 'date-range' },
			{ label: '区域',			name: 'region_id',	type: 'select' },
			{ label: '业务员',		name: 'salesman_id',	type: 'select' },
		],
		// 提交表单列表
		formData : [
			{ label: '合同编号',		name: 'code', 				half:true,  disabled:true },
			{ label: '合同名称',		name: 'name', 				half:true,  disabled:true },
			{ label: '折扣率',		name: 'discount_rate', 		half:true, 	required:true, type:'number'},
			{ label: '延期时间',		name: 'delay', 				half:true, 	required:true, type:'number', afterText:'月'},
			{ label: '新生效时间',	name: 'sign_at', 			half:true,  required:true, type:'date-time', format:1 },
			{ label: '新到期时间',	name: 'contract_validity', 	half:true, 	required:true, type:'date-time', format:1 },
		],
	}
	
	model = {}
	query = { type:'my' }
	status = '99'
	
	componentDidMount(){
		const { type } = this.props
		if(type){ this.query = { type } }
		
		this.getSelect()
		
		if(window.isInit){
			this.fetch()
		}
		
		$fn.fresh.on(this.fetch)
	}
	componentWillUnmount(){
		$fn.fresh.remove()
	}
	// 获取下拉数据
	getSelect = async () => {
		const { forms } = this.state
		$cache.then( async f => {
			// 客户名称
			$fn.setRow(forms, 'hosp_id', await f.getCache({ api:'hospital' } ) )
			// 区域
			$fn.setRow(forms, 'region_id', await f.getCache({ api:'bs_area' } ) )
			// 业务员
			$fn.setRow(forms, 'salesman_id', await f.getCache({ api:'salesman' } ) )
			// 
			this.setState({ forms })
		})
		
	}
	
	// paging
	fetch = () => $fn.fetch.call(this,'bs-contract/index', {param:{enabled:+this.status===99?'':this.status}})
	
	// 表单
	cols = [
		{ title: '合同编号', 		dataIndex: 'code', 				width:100 },
		{ title: '合同名称', 		dataIndex: 'name', 				width:200 },
		{ title: '客户名称', 		dataIndex: 'hosp_name', 		width:200 },
		{ title: '生效时间', 		dataIndex: 'sign_at', 			...$fn.table.time },
		{ title: '到期时间', 		dataIndex: 'contract_validity', ...$fn.table.time },
		{ title: '延期时间(月)', 	dataIndex: 'delay', 			width:100, align:'center'},
		{ title: '折扣率', 			dataIndex: 'discount_rate', 	width:100 },
		{ title: '合同类型', 		dataIndex: 'type', 				width:100, render: text => $fn.getState(contractType, text)  },
		{ title: '状态', 			dataIndex: 'enabled', 			width:100, render: text => $fn.getState(tabsData, text, 'title')  },
		{ title: '创建人（系统）', 	dataIndex: 'empl_name', 		width:150 },
		{ title: '业务员', 			dataIndex: 'salesman_user', 	...$fn.table.name },
		TableControls.controls.call(this, { width: 330 })
	]
	
	// 表格操作按钮
	table_controls = (text, rows, status) => {
		const { uuid, code, enabled } = rows
		return [
			TableControls.pushTo.call(this, '编辑',  `edit?uuid=${uuid}&edit=1` ),
			TableControls.pushTo.call(this, '查看附件',  ()=> this.checAccessoryModalRef.open(rows) ),
			(+enabled===1||+enabled===2)&&TableControls.edit.call(this, null, { uuid }, { label:'续签', rows,
				load: ({ sign_at, contract_validity,uuid }) =>{
					this.formRef.reset(['sign_at','contract_validity','uuid'])
					this.submit = { uuid }
				}
			} ),
			+enabled===0&&Confirm.call(this,'提交','bs-contract/submit', { query:{uuid:[uuid]}, clear:false,onComplete:()=>this.tipModalRef.open() }),
			+enabled===1&&Controls.click.call(this, '终止', ()=>this.abortModalRef.open([uuid])),
			+enabled===5&&Controls.click.call(this, '审核', ()=>this.auditModalRef.open([uuid])),
			(+enabled===1||+enabled===4||+enabled===2||+enabled===3)&&TableControls.pushTo.call(this,'合同签订记录', `contract-record?code=${code}`),
			+enabled===3&&Confirm.call(this,'恢复','bs-contract/revert', { query:{uuid:[uuid]} }),
		]
	}
	
	// 操作按钮
	controls = () => {
		return [
			Controls.pushTo.call(this, '新增',  `edit?edit=2`, { code:'F1'}),
			Controls.imports.call(this, 'bs-contract/import', {op_key: 'BsContractExcel', reconfirm: true}),			// 文件导入
			(+this.status===0||+this.status===99)&& Confirm.call(this,'提交','bs-contract/submit', { isKeys:true, clear:false, onComplete:()=>this.tipModalRef.open() }),
			(+this.status===1||+this.status===99)&& Controls.click.call(this, '终止', ()=>this.abortModalRef.open(this.state.selectedKeys), {isKeys:true}),
			(+this.status===5||+this.status===99)&&Controls.click.call(this, '审核', ()=>this.auditModalRef.open(this.state.selectedKeys), {isKeys:true}),
			(+this.status===3||+this.status===99)&&Confirm.call(this,'恢复','bs-contract/revert', {isKeys:true}),
			// 下载导入模板
			Controls.importTemplate.call(this),
		]
	}
	
	render(){
		return (
			<>
				<Page title='合同管理' controls={this.controls()}>
					{/* 合同管理增加状态 2022/4/21  --马婷 */}
					<Tabs
						data={ tabsData }
						defaultActiveKey = { 0 }
						onTabs = { ({ status }) => {
							this.status = status
							this.setState({data:[],selectedKeys:[]})
							this.fetch()
						}}
					/>
					{/* 搜索 */}
					{ SearchForm.call(this) }
					{/* 表格 */}
					{ Table.call(this, { isInit: window.isInit }) }
				</Page>
				{/* 合同续签 */}
				{ FormModal.call(this,{ title:'合同续签', labelWidth:'s9', width:800, api: 'bs-contract/renew', enter:false}) }
				{/* 查看附件 */}
				<ChecAccessoryModal onRef={ref=>this.checAccessoryModalRef = ref}/>
				{/* 审核 */}
				<AuditModal onRef={ref=>this.auditModalRef = ref} onRefresh={this.fetch} />
				{/* 终止 */}
				<AbortModal onRef={ref=>this.abortModalRef = ref} onRefresh={this.fetch} />
				{/* 提示框 */}
				<TipModal onRef={ref=>this.tipModalRef = ref} />
			</>
		)
	}
}

export default Index